layui.use(['table','layer','jquery','form','songCommon'], function(){
    var layer = layui.layer;
    var table = layui.table;
    var $ = layui.$;
    var form = layui.form;
    var songCommon = layui.songCommon;
    var path;

    var array = [
         {type: 'checkbox', fixed: 'left'}
        ,{field:'name', title:'用户名', edit: 'text'}
        ,{field:'account', title:'账号'}
        ,{field:'sex', title:'性别'}
        ,{field:'phone', title:'手机'}
        ,{field:'status', templet : "#tabState", title:'状态'}
        ,{field:'createTime', title:'加入时间'}
        ,{fixed: 'right', title:'操作', toolbar: '#barDemo',align:'center'}
    ];

    table.render({
        elem: '#tab'
        ,url:'/v1/user/userList'
        ,cellMinWidth: 80
        ,title: '用户数据表'
        ,toolbar: '#toolbarDemo'
        ,limits : [10,30,60,90]
        ,cols: [
            array
        ]
        // ,even: true 开启隔行背景
        ,text: {
            none: '暂无相关数据'
        }
        ,defaultToolbar : ['filter']
        ,id : 'userTable'
        ,page: true
        ,sort: false
    });


    //监听行工具事件
    table.on('tool(tab)', function(obj){
        var data = obj.data;
        if(obj.event === 'del'){
            layer.confirm('您确定要删除选中的数据？删除后,不可恢复', {icon: 3, title:'提示'},function(index){
                var path = "/v1/user/deleteUserById";
                $.post(path,{
                    id : data.id
                },function (data) {
                    if (data.code === 0) {
                        layer.msg("删除成功！");
                        layer.close(index);
                        reloadTab();
                    } else {
                        layer.msg("删除失败！");
                    }
                },"json");
            });
        } else if(obj.event === 'edit'){
            showEditModel(data);
        } else if (obj.event === 'setRole') {
            showUserRole(data);
        }
    });

    // 树形
    var setting = {
        check : {
            enable: true,
            chkStyle: "checkbox",
            chkboxType: { "Y": "", "N": "" },
            nocheckInherit: true
        },
        view: {
            nameIsHTML: true,
            showLine: true,
            selectedMulti: false
        },
        data: {
            simpleData: {
                enable: true
            }
        }
    };
    // 展示用户所属角色
    function showUserRole(data){
        var index  = layer.open({
            type: 1,
            area: ['420px', '500px'], //宽高
            maxmin: true,
            title: "分配角色",
            content: $('#roleTreeForm').html(),
            success : function() {

                var path = '/v1/role/getRoleTreeByUserId?userId=' + data.id;
                $.post(path,function (res) {
                    $.fn.zTree.init($("#userRoleTree"),setting,res);
                    $.fn.zTree.getZTreeObj("userRoleTree").expandAll(true);
                },"json");

                form.on("submit(addUserFrom)",function() {
                    var treeObj = $.fn.zTree.getZTreeObj("userRoleTree");
                    var nodes = treeObj.getCheckedNodes(true);
                    var roleIds = [];
                    for (var k in nodes) {
                        roleIds.push(nodes[k].id);
                    }
                    var path = "/v1/userRole/addUserRoles";
                    layer.load(2);
                    $.post(path, {
                        userId : data.id,
                        roleIds : roleIds.toString()
                    },function (res) {
                        layer.closeAll('loading');
                        if (res.code === 0) {
                            songCommon.showOk("分配角色成功！");
                            layer.close(index);
                        } else if (res === 500) {
                            songCommon.showFail(res.msg);
                        } else {
                            songCommon.showFail("分配角色失败");
                        }
                    },"json");
                    return false;
                });
            }
        });
        $(document).on('click','#btnRoleTreeClose',function(){
            layer.close(index);
        });
    }

    // 刷新表格
    function reloadTab () {
        table.reload('userTable');
    }

    //监听事件
    table.on('toolbar(tab)', function(obj){
        var layEvent = obj.event;
        var checkStatus = table.checkStatus(obj.config.id)
         ,data = checkStatus.data; //获取选中的数据

        switch(layEvent) {
            case 'addUser':
                showEditModel();
                break;

            case 'isAll':
                layer.msg(checkStatus.isAll ? '全选' : '未全选');
                break;

            // 批量删除
            case 'batchDelUser':
                if (data.length === 0) {
                    layer.msg("请选择具体数据！", {time: 3000});
                    return
                }
                var ids = [];
                for (var index in data) {
                    ids.push(data[index].id);
                }
                var path  = "/v1/user/batchDel";
                var param = {
                    ids : ids.toString()
                };
                layer.confirm('您确定要删除选中的数据？删除后,不可恢复', function(index) {
                    $.post(path, param, function (data) {
                        if (data.code === 0) {
                            layer.msg("删除成功！");
                            reloadTab();
                        }
                    }, "json");
                    layer.close(index);
                });
                break;
        };
    });

    // 表单校验
    form.verify({
        name: function(value, item){ //value：表单的值、item：表单的DOM对象
            if (value === "") {
                return "不允许为空";
            }
            if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
                return '用户名不能有特殊字符';
            }
            if(/(^\_)|(\__)|(\_+$)/.test(value)){
                return '用户名首尾不能出现下划线\'_\'';
            }
            if(/^\d+\d+\d$/.test(value)){
                return '用户名不能全为数字';
            }
        }
        ,password: function (value, item) {
            if (value === "") {
               return "不允许为空";
            }
            if (!/^[\S]{6,12}$/.test(value)) {
                return '密码必须6到12位，且不能出现空格'
            }
        }
    });

    // 单元格编辑
    table.on('edit(tab)', function(obj){
        var value = obj.value //得到修改后的值
            ,data = obj.data //得到所在行所有键值
            ,field = obj.field; //得到字段

        var path = "/v1/user/updateUserName";
        var param = {
            name : value,
            id : data.id
        }
        $.post(path,param,function (data) {
            if (data.code === 0) {
                layer.msg("更新成功!");
                reloadTab();
            }
        },"json");
    });

    /*
    监听表格选中事件
    table.on('row(tab)', function(obj){
        var data = obj.data;
        layer.alert(JSON.stringify(data), {
            title: '当前行数据：'
        });
    });
    */

    $(document).on('click','#btnClose',function(){
        layer.close(layer.index);
    });

    // 编辑框
    function showEditModel(data) {
        var index  = layer.open({
            type: 1,
            area: ['520px', '440px'], //宽高
            maxmin: true,
            title: data ? '修改用户' : '添加用户',
            content: $('#userForm').html(),
            success : function (layero, index) {
                path = "/v1/user/addUser";
                form.render(); // 动态生成执行渲染
                // 回显user数据
                if (data) {
                    form.val('userForm', data);
                    path = "/v1/user/updateUser";
                }
                //监听提交
                form.on('submit(addUserFrom)', function (rowData) {
                     $.post(path, rowData.field, function(ajaxData) {
                        layer.closeAll('loading');
                        if (ajaxData.code === 0) {
                            layer.msg("操作成功！");
                            layer.close(index);
                            reloadTab();
                        } else {
                            layer.msg(ajaxData.msg, {icon: 2});
                        }
                    }, "json");
                    return false;
                });
            }
        });
        $(document).on('click','#btnClose',function(){
            layer.close(index);
        });
    }

    // 重置事件
    $("#reset").bind("click",function () {
       $("#account").val("");
       $("#name").val("");
       $("#phone").val("");
    });

    // 搜索
    $("#userBtnSearch").bind("click",function() {
        table.reload('userTable', {
            where: {
                account : $("#account").val(),
                name : $("#name").val(),
                phone : $("#phone").val()
            }
        });
    });

    // 修改user状态
    form.on('switch(updateState)', function (obj) {
        layer.load(2);
        var url = "/v1/user/updateUser";
        $.post(url,{
            id : obj.elem.value,
            status : obj.elem.checked ? 0 : 1
        },function (data) {
            layer.closeAll('loading');
            if (data.code === 0) {
                songCommon.showOk("更新成功！");
            } else {
                songCommon.showFail("更新失败！");
            }
        },"json");
    });

});



